package org.linlinjava.litemall.db.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;

import org.springframework.util.ResourceUtils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

/**
 * 桌面二维码生成
 */
public class QRCodeGenerator {

	/**
	 * 生成二维码
	 * @param httpTcp  	协议
	 * @param tableNo	桌号
	 * @param imgSize	图片大小
	 * @return
	 */
	public static byte[] createPicBlob(String httpTcp ,String tableNo , Integer imgSize){
		String generateQRCodeImage = generateQRCodeImage(
				httpTcp+"?tableNo="+tableNo, imgSize, tableNo+".jpg");

		File file = new File(generateQRCodeImage);
		byte[] imageData = new byte[(int)file.length()-1];
		try {
			FileInputStream is= new FileInputStream(file);
			is.read(imageData);
			is.close();
			file.delete();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return imageData;
	}

	/**
	 * 生成二维码
	 * @param text  	文本
	 * @param imgSize  	二维码大小
	 * @param fileName	文件名
	 * @throws WriterException
	 * @throws IOException
	 */
	public static String generateQRCodeImage(String text, Integer imgSize, String fileName) {
		QRCodeWriter qrCodeWriter = new QRCodeWriter();
		String basePath = getResourceBasePath();
		String studentResourcePath = "";
		//打包成jar后/src/main/resources/路径不存在直接在jar所在路径生成图片
		if (new File(basePath+"/src/main/resources/").exists()) {
			studentResourcePath = new File(basePath, "/src/main/resources/").getAbsolutePath();
		}else {
			studentResourcePath = new File(basePath, "").getAbsolutePath();
		}
		try {
			BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, imgSize, imgSize);
			Path path = FileSystems.getDefault().getPath(studentResourcePath+"/"+fileName);
			MatrixToImageWriter.writeToPath(bitMatrix, "png", path);
		} catch (WriterException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return studentResourcePath+"/"+fileName;

	}

	/**
	 * 获取项目根路径
	 *
	 * @return
	 */
	private static String getResourceBasePath() {
		// 获取跟目录
		File path = null;
		try {
			path = new File(ResourceUtils.getURL("classpath:").getPath());
		} catch (FileNotFoundException e) {
			// nothing to do
		}
		if (path == null || !path.exists()) {
			path = new File("");
		}

		String pathStr = path.getAbsolutePath();
		// 如果是在eclipse中运行，则和target同级目录,如果是jar部署到服务器，则默认和jar包同级
		if (pathStr.indexOf("\\target\\classes") != -1) {
			pathStr = pathStr.replace("\\target\\classes", "");
		}else if (pathStr.indexOf("\\target\\test-classes") != -1) {
			pathStr = pathStr.replace("\\target\\test-classes", "");
		}
		return pathStr;
	}
}
